package server;


import org.dom4j.Element;

public class Mapper extends BaseContainer<Host> {
    //    private Map<String, Servlet> servletUriMap = new HashMap<>();
//
//    public void registerServlet(Host host, Context context, Wrapper wrapper) {
//        String uri = String.format("%s/%s/")
//    }
    private Host defaultHost;

    private static String[] analysisUrl(String url) {
        String[] urlParts = new String[2];
        String[] schemaParts = url.split("://");

        String truncatedUrl = url.substring(1);
        // 获取上下文名，此处忽略 ROOT 上下文的情况
        String contextName = "";
        int contextIdx = truncatedUrl.indexOf("/");
        if (contextIdx >= 0) {
            contextName = truncatedUrl.substring(0, contextIdx);
            urlParts[0] = contextName;
        }

        // 获取 servlet 映射路径
        String servletPattern = truncatedUrl.substring(contextName.length());
        int paramIdx = servletPattern.indexOf("?");
        if (paramIdx >= 0) {
            servletPattern = servletPattern.substring(0, paramIdx);
        }
        urlParts[1] = servletPattern;

        return urlParts;
    }

    public static void main(String[] args) {
        String url = "http://10.0.3.3:8080/rrot/123/5555?xxx=444";
        String[] urlParts = analysisUrl(url);
        System.out.println(urlParts.length);
    }

    /**
     * 从 Host 配置节点读取配置，实例化 Host，并逐层解析和初始化下级容器
     *
     * @param hostNode
     * @throws Exception
     */
    public void addHost(Element hostNode) throws Exception {
        // 实例化 Host，并逐层解析和初始化下级容器
        Host host = Host.build(hostNode);
        // 以 Host name 为 KEY 加入容器
        addChildren(host.getName(), host);

        // 将第一个解析到的 Host 作为默认 Host，模拟  default host 配置
        if (defaultHost == null) {
            defaultHost = host;
        }
    }

    /**
     * 根据请求的 hostName 或 IP，以及请求 url 找到处理 servlet 实例
     *
     * @param hostNameOrIp
     * @param url
     * @return
     */
    public Servlet getServletInstance(String hostNameOrIp, String url) {
        // 解析URL，找出 context 和 urlPattern
        String[] urlParts = analysisUrl(url);
        // 从容器中获取 Host 实例
        Host host = getHost(hostNameOrIp);
        if (host != null) {
            // 获取 context，此处忽略 ROOT 上下文场景
            Context context = host.getContext(urlParts[0]);
            if (context != null) {
                // 获取 servlet，此处忽略模糊匹配的场景，直接精确匹配 urlPattern
                Wrapper wrapper = context.getWrapper(urlParts[1]);
                if (wrapper != null) {
                    // 从 wrapper 中取出 servlet instance，以处理请求
                    return wrapper.getServletInstance();
                }
            }
        }
        return null;
    }

    // 根据 hostName  或 IP 获取 Host 实例
    private Host getHost(String hostName) {
        Host host = getChild(hostName);
        if (host == null) {
            host = defaultHost;
        }
        return host;
    }
}
